import { OneModal } from '@/components/one-ui';
import React, { Ref, useRef, useState, useMemo, useEffect } from 'react';
import { IOneModalRef } from '@/pages/type';
import { Button, Spin, message, Steps, Space, Select } from 'antd';
import { AcceptanceManageAPI } from '../common/type';
import { onCloseModalCommon } from '@/utils';
import { batchAddMaterialServices } from '../services';
import cls from 'classnames';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { UploadFirstStep } from './UploadFirstStep';
import { UploadSecordStep } from './UploadSecordStep';
import { UploadThirdStep } from './UploadThirdStep';

// import '../common/styles.less'
export const UploadModal: React.FC<AcceptanceManageAPI.IUploadModal> = ({ curRes, onClose, reloadManage }) => {
  const prefix = 'material-upload-';

  /** 子组件表单ref  第二步步骤 */
  const uploadFormRef = useRef<AcceptanceManageAPI.IUploadFormRef>(null);

  /** 定义步骤 */
  const steps = [
    {
      title: '上传文件',
    },
    {
      title: '数据校验',
    },
    {
      title: '数据确认',
    },
  ];

  /**弹框的ref*/
  const uploadModalRef: Ref<IOneModalRef> = useRef(null);

  /** 当前步骤 */
  const [current, setCurrent] = useState<number>(0);

  /** 当前选择的类型 */
  const [selectMaterialType, setSelectMaterialType] = useState<string>('');

  /** 保存导入的数据 */
  const [uploadList, setUploadList] = useState<Record<string, any>[]>([]);

  /**点击确定方法*/
  const onUploadOK = () => {
    uploadFormRef?.current?.secordStepForm?.validateFields()?.then((values: any) => {
      let reqObj = {
        mmaterialList: [...values?.table],
      };
      batchAddMaterialRun(reqObj);
    });
  };

  /**修改当前选中的材料类型*/
  const changeMaterialType = (value: string) => {
    setSelectMaterialType(value);
  };

  /**点击取消方法*/
  const onUploadCancel = () => {
    onCloseModalCommon(uploadModalRef);
  };

  /**点击确认方法*/
  const onUploadSure = () => {
    reloadManage();
    onCloseModalCommon(uploadModalRef);
  };

  /**批量添加Callback*/
  const batchAddMaterialCallback = (res: any) => {
    if (res?.msgFlag) {
      message.success(res?.msg);
      // onCloseModalCommon(uploadModalRef);
      reloadManage();
    }
  };

  /**添加方法services*/
  const { batchAddMaterialRun, batchAddMaterialLoading, batchAddMaterialData } = batchAddMaterialServices(batchAddMaterialCallback);

  /**监听有无数据 有数据下一步按钮不禁用*/
  const allUploadList = useMemo(() => {
    if (uploadList && uploadList?.length > 0) {
      return true;
    }
    return false;
  }, [uploadList]);

  /**公用loading*/
  const allLoading = useMemo(() => {
    // if () {
    //   return true;
    // } else {
    //   return false;
    // }
    return false;
  }, []);

  /** 请求完批量接口  如果有数据 自动跳到最后一步 */
  useEffect(() => {
    if (batchAddMaterialData && batchAddMaterialData?.length > 0) {
      setCurrent(2);
    }
  }, [batchAddMaterialData]);

  /** 更新导入的数据 */
  const reloadUploadList = (dataInfo: Record<string, any>[]) => {
    setUploadList(dataInfo);
  };

  /** 底部按钮 */
  const footerModal = useMemo(() => {
    return (
      <div className={cls(prefix + 'footer')}>
        <Space>
          <Button
            key="back"
            onClick={onUploadCancel}
            // icon={<CloseCircleOutlined />}
          >
            关闭
          </Button>

          {current === 0 && (
            <Button
              // disabled={allUploadList ? false : true}
              onClick={() => {
                if (allUploadList) {
                  setCurrent(1);
                } else {
                  message.error('未上传文件或文件解析错误');
                }
              }}
            >
              下一步
            </Button>
          )}
          {current === 1 && (
            <>
              <Button
                onClick={() => {
                  setCurrent(0);
                }}
                type="primary"
              >
                上一步
              </Button>

              <Button key="submit" type="primary" loading={allLoading} onClick={onUploadOK}>
                下一步
              </Button>
            </>
          )}
          {current === 2 && (
            <>
              <Button type="primary" onClick={onUploadSure}>
                确认
              </Button>
            </>
          )}
        </Space>
      </div>
    );
  }, [curRes, current, allLoading, allUploadList]);

  /**改变步骤条 */
  const handleChangeSteps = (current: number) => {
    if (current === 0) {
      setUploadList(uploadList);
      setCurrent(0);
    } else if (current === 1) {
      setUploadList(uploadList);
      setCurrent(1);
    } else if (current === 2) {
      setCurrent(2);
    }
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={uploadModalRef}
        title={'导入文件'}
        onCancel={onClose}
        onOk={onUploadOK}
        footer={footerModal}
        width={document.body.clientWidth * 0.65}
        bodyStyle={{
          height: document.body.clientHeight * 0.55,
          padding: '5px 10px',
        }}
        centered
      >
        <Spin spinning={allLoading || batchAddMaterialLoading}>
          <div
            className={'material-upload'}
            style={{
              padding: '0 30px',
            }}
          >
            <div className={cls(prefix + 'step')}>
              <Steps current={current} size={'small'} items={steps} onChange={handleChangeSteps} />
            </div>
            <div className={cls(prefix + 'content')}>
              <ScrollBarLayout>
                {current === 0 && (
                  <UploadFirstStep
                    prefix={prefix}
                    current={current}
                    reloadUploadList={reloadUploadList}
                    selectMaterialType={selectMaterialType}
                    changeMaterialType={changeMaterialType}
                  />
                )}
                {current === 1 && <UploadSecordStep prefix={prefix} current={current} tableList={uploadList} ref={uploadFormRef} />}
                {current === 2 && <UploadThirdStep prefix={prefix} current={current} total={batchAddMaterialData?.length || uploadList?.length || 0} />}
              </ScrollBarLayout>
            </div>
          </div>
        </Spin>
      </OneModal>
    </>
  );
};
